package de.koller.worlders.engine.tiles.landscape.generator.universe;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.Line2D;
import java.awt.image.BufferedImage;
import java.util.Random;

public class Cave implements IUniverseGenerator {

	private static final int MAX_ITERATIONS = 300;
	private static final double MAX_BEND = 0.5;
	private static final double MIN_SEGMENT_LENGTH = 1;
	private static final double MAX_SEGMENT_LENGTH = 5;
	private static final double BRANCH_CHANCE = 0.01;
	
	private static final Random rnd = new Random();
	private int borderColor = 0xffff0000;
	
	public void addRoot( BufferedImage map ) {
		Graphics2D g = map.createGraphics();
		g.setColor( new Color( borderColor ) );
		
		g.setStroke( new BasicStroke( 3, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND ) );

		addLineSegment( g, map.getWidth()/2, map.getHeight()/2, 
				rnd.nextDouble()*Math.PI*2, 0 );
	}
	
	private void addLineSegment( Graphics2D g, double x, double y, double previousSegmentDirection, int iteration ) {
		if( iteration > MAX_ITERATIONS )
			return;
		
		double segmentLength = MIN_SEGMENT_LENGTH + rnd.nextDouble() * (MAX_SEGMENT_LENGTH-MIN_SEGMENT_LENGTH);
		double segmentDirection = previousSegmentDirection + rnd.nextDouble()*MAX_BEND*2 - MAX_BEND;
		double newX = x + Math.cos( segmentDirection ) * segmentLength;
		double newY = y + Math.sin( segmentDirection ) * segmentLength;
		
		g.draw( new Line2D.Double( x, y, newX, newY ) );
		
		double b = rnd.nextDouble();
		if( b <= BRANCH_CHANCE ) 
			addLineSegment( g, newX, newY, 
					rnd.nextDouble()*2*Math.PI, 
					rnd.nextInt( MAX_ITERATIONS ) );
		
		addLineSegment( g, newX, newY, segmentDirection, iteration+1 );
	}
				
	@Override
	public void setBorderColor( int color ) {
		borderColor = color;
	}
	
}
